package com.hc.java.lock;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 对比 synchronized、Lock
 * 单线程时开销： synchronized优于Lock
 *
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/6/6 16:43
 */
public class 锁对比 {

    public static void main(String[] args) {
        long l1 = System.currentTimeMillis();
        automic();
        long l2 = System.currentTimeMillis();
        sync();
        long l3 = System.currentTimeMillis();
        i1();
        long l4 = System.currentTimeMillis();
        System.out.println("atomic:" + (l2 - l1) + ": v=" + atom1.get());
        System.out.println("sync:" + (l3 - l2) + ": v=" + sync1);
        System.out.println("无锁:" + (l4 - l3) + ": v=" + i1);
    }

    private static int i1 = 0;

    private static void i1() {
        for (int i = 0; i < 10 * 10000 * 10000; i++) {
            i1++;
        }
    }

    private static int sync1 = 0;

    private synchronized static void sync() {
        for (int i = 0; i < 10 * 10000 * 10000; i++) {
            sync1++;
        }
    }

    private static AtomicInteger atom1 = new AtomicInteger(0);

    private static void automic() {
        for (int i = 0; i < 10 * 10000 * 10000; i++) {
            atom1.addAndGet(1);
        }
    }
}
